# coding=utf-8
#
# 版权所有 2011 沙发客团队
# 遵循Apache License 2.0协议
#    具体见 http://www.apache.org/licenses/LICENSE-2.0
#
# 日志操作模块，此类是唯一实例化
#

import logging, os

class Logger:
    """ 管理系统内部的所有资源信息以及临界变量 """
    # =============================================
    # 唯一实例开始位置
    # =============================================
    class __impl:
        """ Implementation of the singleton interface """

    # storage for the instance reference
    __instance = None
    
    def __getattr__(self, attr):
        """ Delegate access to implementation """
        return getattr(self.__instance, attr)

    def __setattr__(self, attr, value):
        """ Delegate access to implementation """
        return setattr(self.__instance, attr, value)
    # =============================================
    # 唯一实例结束位置
    # =============================================
    

    def __init__(self, path = "shafake.log", terminal = True):
        """ Create singleton instance """
        if Logger.__instance is None:
            # Create and remember instance
            Logger.__instance = Logger.__impl()

            #
            # 本地定义日志操作
            #
            logger = logging.getLogger(os.path.basename(path))
            logger.setLevel(logging.DEBUG)
    
            self._path = path
            #
            # 添加文件日志输出和控制台输出
            #
            hdlr = logging.FileHandler(path, 'a', 'utf-8')
            
            # 设置输出文件格式
            formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
            hdlr.setFormatter(formatter)
            
            # 添加日志处理模块
            logger.addHandler(hdlr)
            
            if terminal == True:
                ch = logging.StreamHandler()
                ch.setFormatter(formatter)
                logger.addHandler(ch)
            #
    
            self._logger = logger
    
    # 处理不同日志的类型
    def debug(self, msg, *args, **kwargs):
        self._logger.debug(msg, *args, **kwargs)
        
    def info(self, msg, *args, **kwargs): 
        self._logger.info(msg, *args, **kwargs)
        
    def warning(self, msg, *args, **kwargs):
        self._logger.warning(msg, *args, **kwargs)
        
    def error(self, msg, *args, **kwargs):
        self._logger.error(msg, *args, **kwargs)
        
    def exception(self, msg, *args, **kwargs):
        self._logger.exception(msg, *args, **kwargs)
        
    def critical(self, msg, *args, **kwargs):
        self._logger.critical(msg, *args, **kwargs)

if __name__ == '__main__':
    logger = Logger(terminal=True)
    logger.debug("zz")
    logger.info("aaaaa")
    logger.warning("add")